package com.xm.dao.background;

import com.xm.entity.Message;
import com.xm.entity.Page;
import com.xm.exception.SqlErrorException;
import com.xm.util.BaseUtil;
import org.intellij.lang.annotations.Language;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 活动Dao层
 *
 * @author 陈盼
 * @date 2023-12-28 下午 06:29
 */
public class MessageDao extends BaseUtil {
    /**
     * 删除活动
     *
     * @param messageId 消息Id
     * @throws SqlErrorException SQL执行异常
     */
    public boolean deleteMessage(String messageId) throws SqlErrorException {
        @Language("SQL")
        String sql = "delete from message where message_id=?";
        int id = executeUpdate(sql, messageId);
        return id != 0;
    }

    /**
     * 添加或修改活动
     * 如果传了getMessageId则修改没有则新增
     *
     * @param message 账号实体类
     * @throws SqlErrorException SQL执行异常
     */
    public boolean addMessage(Message message) throws SqlErrorException {
        if (message.getMessageId() == null) {
            // 添加收货地址
            @Language("SQL")
            String sql = "INSERT INTO message (message_title, message_context, message_type) VALUES (?, ?, ?)";
            int id = executeUpdate(sql, message.getMessageTitle(), message.getMessageContext(), message.getMessageType());
            return id != 0;
        } else {
            // 修改收货地址
            @Language("SQL")
            String sql = "UPDATE message SET message_title = ?, message_context = ?, message_type = ? WHERE message_id = ?";
            int id = executeUpdate(sql, message.getMessageTitle(), message.getMessageContext(), message.getMessageType(), message.getMessageId());
            return id != 0;
        }
    }


    /**
     * 查询全部活动
     *
     * @return 活动列表
     */
    public List<Message> findAll() {
        // SQL语句
        @Language("SQL")
        String sql = "select * from message order by message_id asc";
        // 执行查询操作
        ResultSet rs = null;
        List<Message> messageList = new ArrayList<>();
        try {
            rs = executeQuery(sql);
            // 遍历结果集
            while (rs.next()) {
                Message message = new Message();
                message.setMessageId(rs.getInt("message_id"));
                message.setMessageTitle(rs.getString("message_title"));
                message.setMessageContext(rs.getString("message_context"));
                message.setMessageType(rs.getInt("message_type"));
                message.setMassageDate(rs.getDate("message_date"));
                messageList.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs);
        }
        return messageList;
    }

    /**
     * 分页查询
     *
     * @param pageNumber 分页页数
     * @param pageSize   每页数量
     * @return page<对象>
     */
    public Page<Message> pagination(int pageNumber, int pageSize, String activityDate, String activityMc, String dateBegin, String dateEnd, String messageType) {
        Page<Message> page = new Page<>();
        List<Message> list = new ArrayList<>();
        @Language("SQL")
        String countSql = "SELECT COUNT(*) FROM message";
        @Language("SQL")
        String dataSql = "SELECT * FROM message where 1=1";

        System.out.println(dateBegin + "--------------------" + dateEnd);
        if (activityMc != null) {
            if (isNumeric(activityMc)) {
                dataSql += " and message_id like '%" + activityMc + "%'";
            } else {
                dataSql += " and message_title like '%" + activityMc + "%'";
            }
        }

        if ("".equals(dateBegin)) {
            dateBegin = null;
        }
        if ("".equals(dateEnd)) {
            dateEnd = null;
        }
        if (dateBegin != null && dateEnd != null) {
            dataSql += " and message_date BETWEEN '" + dateBegin + "' AND '" + dateEnd + "'";
        }

        if (dateBegin != null && dateEnd == null) {
            dataSql += " and message_date BETWEEN '" + dateBegin + "' AND NOW()";
        } else if (dateBegin == null && dateEnd != null) {
            dataSql += " and message_date BETWEEN '2010-03-03' AND '" + dateEnd + "'";
        }

        System.out.println(messageType + "----------------");
        if (messageType != null) {
            dataSql += " and " + messageType + "=message_type";
        }

        String data = "0";

        String order = " order by message_date desc";
        if (activityDate != null) {
            if (data.equals(activityDate)) {
                order = " order by message_date desc";
            } else {
                order = " order by message_date asc";
            }
        }
        dataSql += order;

        dataSql += " LIMIT ?, ?";
        ResultSet countRs = null;
        ResultSet dataRs = null;
        try {
            // 查询总数
            countRs = executeQuery(countSql);
            if (countRs.next()) {
                int count = countRs.getInt(1);
                page.setCount(count);
                page.setTotalPages(pageSize);
            }

            // 分页查询数据
            int offset = (pageNumber - 1) * pageSize;
            dataRs = executeQuery(dataSql, offset, pageSize);
            while (dataRs.next()) {
                Message message = extractMessageFromResultSet(dataRs);
                list.add(message);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(countRs);
            close(dataRs);
        }
        page.setData(list);
        page.setPageNumber(pageNumber);
        page.setPageSize(pageSize);
        return page;
    }

    /**
     * 查询的参数
     *
     * @param rs 查询结果集
     * @return 对象
     * @throws SQLException 抛出错误
     */
    private Message extractMessageFromResultSet(ResultSet rs) throws SQLException {
        Message message = new Message();
        message.setMessageId(rs.getInt("message_id"));
        message.setMessageTitle(rs.getString("message_title"));
        message.setMessageContext(rs.getString("message_context"));
        message.setMessageType(rs.getInt("message_type"));
        message.setMassageDate(rs.getDate("message_date"));
        return message;
    }

    /**
     * 判断是不是数字
     *
     * @param str 字符串
     * @return turn 是数字，false 不是数字
     */
    public static boolean isNumeric(String str) {
        return str != null && str.matches("-?\\d+(\\.\\d+)?");
    }

}
